<template>
  <div class="personalCenter_container padding-1 pt-2">
    <div class="personalCenter_container_user mb-1">
      <img class="user_img" :src="userInfo.image" @error="handleImageError" alt="">
      <div class="personalCenter_container_userInfo">
        <div class="userInfo_top mb-0"  @click="goPersonalSetting">
          <div class="userInfo_top_name">{{userInfo.name}}</div>
          <img class="userInfo_top_level ml-0 mr-0" :src="levelIcon" alt="" @click.stop="clickLevelIcon">
          <img class="userInfo_top_up" src="@/image/personalCenter/image.png" alt="">
          <span :class="[userInfo.yield >= 0 ? 'green_icon' : 'red_icon']">{{ userInfo.yield}}%</span>
        </div>
        <div class="userInfo_bottom">{{ userInfo.account }}</div>
      </div>
      <div class="user_setting" @click="goSystemSettings">
        <img src="@/image/personalCenter/setting.png" alt="">
      </div>
    </div>
    <div class="personalCenter_container_property br-16 mb-1">
      <div class="property_top padding-1">
        <div class="property_top_label">
          <span class="mr-0 ">{{ $t("总资产") }}</span>
          <img v-if="showProperty" src="@/image/personalCenter/icon_xianshi@1x.png" @click="showProperty = !showProperty" alt="">
          <img v-else src="@/image/personalCenter/icon_yincang@1x.png" @click="showProperty = !showProperty" alt="">
        </div>
        <div class="property_top_value">
          <div v-if="showProperty">
            <span class="property_top_value_sps mr-0">{{ userInfo.totalAssets }}</span>
            <span class="mr-0">{{userInfo.currency }}</span>
          </div>
          <div v-else class="mr-0">********</div>
          <!-- <img src="@/image/personalCenter/arrow@1x.png" alt=""> -->
        </div>
        <div class="property_top_label">
          <span class="mr-0">{{ $t("今日盈利") }}</span>
          <span @click="datePopShow = true">{{ today }}</span>
        </div>
        <div class="property_top_value">
          <span class="property_top_value_sp">{{ userInfo.todayProfit + ' / ' + userInfo.todayRate + "%" }}</span>
        </div>
      </div>
      <div class="property_bottom pr-1 pl-1">
        <div class="property_bottom_item" v-for="(item, index) in propertyOperBtns" :key="index" @click="goGoupRoute(item.id)">
          <img :src="item.url" alt="">
          <span class="property_bottom_item_name">{{ item.name }}</span>
        </div>
      </div>
      <div class="property_history" @click="goPersonalHistory">
        <span class="mr-0">{{ $t("历史记录") }}</span>
        <img src="@/image/aiQuantization/indexTop/arrow.png" alt="">
      </div>
    </div>
    <div class="personalCenter_container_banner mb-1 pr-1" @click="goInvite">
      <div class="banner_item">
        <div class="banner_item_label mb-1">
          <span>{{ $t("邀请好友一同参加") }}</span>
          <span class="green_icon">{{ $t("SPACE") }}</span>
        </div>
        <div class="banner_item_value">{{ $t("共享每周奖池的丰厚奖励") }}</div>
      </div>
    </div>
    <div class="personalCenter_container_tabs">
      <van-tabs v-model="active" color="#0086FF" background="#0C1527" title-active-color="#0086FF" title-inactive-color="#FFFFFF" :swipeable="true" :animated="true">
        <van-tab :title="$t('币种')">
          <div class="personalCenter_container_tabs_item br-8 mt-0 padding-0" v-for="(item , index) in currencyList" :key="index" @click="goCurrencyRoute(item)">
            <img :src="item.url" alt="">
            <div class="personalCenter_container_tabs_item_info">
              <div class="tabs_item_info_title">
                <span>{{item.name}}</span>
                <span>{{item.balance}}</span>
              </div>
              <div class="tabs_item_info_label">
                <span>{{item.label}}</span>
                <span>{{item.price}}&nbsp;{{ userInfo.currency }}</span>
              </div>
            </div>
          </div>
        </van-tab>
        <van-tab :title="$t('优惠券')">
          <div v-if="couponList.length">
            <div :class="['couponList_items' ,'br-16' ,'mt-1',item.status == 1 ? 'use_bg' : 'past_bg']" v-for="(item,index) in couponList" :key="index" >
              <div class="couponList_item_left">
                <div class="item_left_title mb-0">
                  <span class="item_left_title_price mr-0">{{item.price}}</span>
                  <span>{{item.currency}}</span>
                </div>
                <div class="item_left_value">
                  {{  $t("满 {amount} 可用",{amount:Number(item.meet).toFixed(0)}) }}
                </div>
              </div>
              <div class="couponList_item_right">
                <div class="couponList_item_right_left">
                  <div class="couponList_item_right_title">{{item.name}}</div>
                  <div class="couponList_item_right_content">
                    <div class="couponList_item_right_time">
                      <div>{{item.startTime}}</div>
                      <div v-if="item.endTime">- {{item.endTime}}</div>
                    </div>
                    
                  </div>
                </div>
                <div class="couponList_item_right_right">
                  <button class="couponList_item_right_button" @click="goAiQuantization(item.status)">{{item.status == 1 ? $t('立即使用') : item.status == 2? $t('已使用') : $t('已过期')}}</button>
                </div>
              </div>
              
            </div>
          </div>
          <van-empty v-else></van-empty>
        </van-tab>
      </van-tabs>
    </div>

    <!-- 等级弹窗 -->
    <div class="personalCenter_container_popBox" v-if="levelPopShow">
        <div class="popBox_bg">
          <img src="@/image/personalCenter/icon_tc_guanbi@1x.png" class="popBox_close"  @click="levelPopShow = false" alt="">
          <div class="popBox_content padding-1">
            <div class="popBox_content_card padding-1 mb-1">
              <div class="card_cell mb-0">
                <div class="card_cell_label clear"></div>
                <div class="card_cell_label">{{ $t('直推成员') }}</div>
                <div class="card_cell_label">{{ $t("直推套餐金额(SUSD)") }}</div>
              </div>
              <div class="" v-for="(item, index) in disposeLevelS" :key="index">
                <div class="card_cell mb-0">
                  <div class="card_cell_label mr-1 clear"><img :src="item.image" alt=""></div>
                  <div class="card_cell_label">
                    <div class="label_num mr-0">
                      {{ item.direct_num }}
                    </div>
                    <div class="label_num" v-if="item.child_num">
                      <span class="mr-0">≥{{ item.child_num }}</span>
                      <img :src="getLevelIcon(item.id - 1)" alt="">
                    </div>
                  </div>
                  <div class="card_cell_label">
                    <span class="label_money label_num">≥{{ item.money }}</span>
                  </div>
                </div>
                <div class="card_cell mb-0" style="color: #32D2B9;">({{$t('AI交易收入增加') + ' ' + item.rate + '%'}})</div>
              </div>
            </div>
            <div class="popBox_content_card card_second padding-1">
              <div class="card_cell mb-0">
                <div class="card_cell_label clear"></div>
                <div class="card_cell_label">{{ $t('直推成员') }}</div>
                <div class="card_cell_label">{{ $t('团队套餐金额 (SUSD)') }}</div>
                <div class="card_cell_label">{{ $t("股权") }}</div>
              </div>
              <div class="" v-for="(item, index) in disposeLevelT" :key="index">
                <div :class="[index == 0?'': 'mb-0' , 'card_cell']">
                  <div class="card_cell_label mr-1 clear"><img :src="item.image" alt=""></div>
                  <div class="card_cell_label warp_box" :class="[item.money?'small_width':'']">
                    <div class="label_num" v-if="item.direct_num">
                      {{ item.direct_num }}
                    </div>
                    <div class="label_num" v-if="item.child_num && index != 0">
                      <span class="mr-0">≥{{ item.child_num }}</span>
                      <img :src="getLevelIcon(item.id - 1)" alt="">
                    </div>
                  </div>
                  <div :class="['card_cell_label' , item.money?'big_width':'clear']">
                    <span class="label_money label_num" :class="[item.money?'':'clear']" v-if="item.money">≥{{ item.money }}</span>
                  </div>
                  <div class="card_cell_label">
                    <span class="label_stock label_num">{{ item.stockRights }}</span>
                  </div>
                </div>
                <div class="card_cell mb-0" style="margin-top: -0.5rem;" v-if="index == 0">
                  <div class="card_cell_label mr-1 clear"></div>
                  <div class="card_cell_label warp_box">
                    <div class="label_num">
                      <span class="mr-0">≥{{ item.child_num }}</span>
                      <img :src="getLevelIcon(item.id - 1)" alt="">
                    </div>
                  </div>
                  <div class="card_cell_label"></div>
                  <div class="card_cell_label"></div>
                </div>
                <div class="card_cell mb-0" style="color: #32D2B9;">({{$t('AI交易收入增加') + ' ' + item.rate + '%'}})</div>
              </div>
            </div>
          </div>
        </div>
    </div>
    <van-calendar v-model="datePopShow" :min-date="minDate" title=" "  color="#005cdf" :max-date="maxDate" :confirm-text="$t('确认')"  @confirm="onConfirm"/>
  </div>
</template>

<script>
import { getUserInfo } from "@/request/personalCenter";
import { confirmDialog , formatNumberWithCommas } from '@/utils'
import { getInvestmentInfo, getUserLevelDes } from "@/request/aiQuantization";
import BusinessUtils from '@/utils/business';
export default {
	name : "PersonalCenter",
  data(){
    return {
      userInfo:{
        image: require("@/image/personalCenter/head.png"),
        yield: 0,
        name: '',
        account: '',
        totalAssets: "",
        todayProfit: '',
        currency:'USD',
        todayRate: '',
      },
      defaultImage: require("@/image/personalCenter/head.png"), // 备用展示用户头像
      showProperty: true,
      today: `${new Date().getMonth() + 1 < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1 }/${new Date().getDate()}/${new Date().getFullYear()} `,
      active: this.$t('币种'),
      propertyOperBtns:[
        {
          id:1,
          name: this.$t("充值"),
          url: require("@/image/personalCenter/topUp.png")
        },
        {
          id:2,
          name: this.$t("提现"),
          url: require("@/image/personalCenter/withdraw.png")
        },
        {
          id:3,
          name: this.$t("闪兑"),
          url: require("@/image/personalCenter/flashExchange.png")
        },
      ],
      currencyList:[
        {
          name: this.$t("USDT"),
          url: require("@/image/personalCenter/USDT.png"),
          label: this.$t("Tether US"),
          balance: 0,
          price: 0,
        },
        {
          name: this.$t("USDC"),
          url: require("@/image/personalCenter/USDC.png"),
          label: this.$t("Tether UC"),
          balance: 0,
          price: 0,
        },
        {
          name: this.$t("SUSD"),
          url: require("@/image/aiQuantization/indexContent/SUSD.png"),
          label: this.$t("SpaceAI US"),
          balance: 0,
          price: 0,
        },
        {
          name: this.$t("SAT"),
          url: require("@/image/aiQuantization/indexContent/SAT.png"),
          label: this.$t("SpaceAI Token"),
          balance: 0,
          price: 0,
        },
      ],
      couponList: [],
      couponList: [],
      levelPopShow: false,
      datePopShow: false,
      maxDate: new Date(),
      isLevelOn: false,// 等级功能是否开启
    }
  },

  mounted(){
    sessionStorage.removeItem('CurrencyDetail')
    this.getUserInfo()
    this.getUserLevelDes()
  },
  computed: {
    levelIcon(){
      if(this.userInfo.level){
        return BusinessUtils.getLevelIcon(this.userInfo.level.id);
      }else{
        return BusinessUtils.getLevelIcon(0);
      }
    },

    disposeLevelS(){
      return this.LevelS;
    },
    disposeLevelT(){
      return this.LevelT;
    },
    minDate(){
      if(this.userInfo.created_at){
        return new Date(this.userInfo.created_at)
      }
      const currentDate = new Date();
      const currentMonth = currentDate.getMonth();
      const newMonth = currentMonth - 6;

      if (newMonth < 0) {
        // 计算需要减少的年份
        const yearToSubtract = Math.ceil(Math.abs(newMonth) / 12);
        // 调整年份
        currentDate.setFullYear(currentDate.getFullYear() - yearToSubtract);
        // 调整月份，使用取模运算得到正确的月份
        currentDate.setMonth(12 + (newMonth % 12));
      } else {
        currentDate.setMonth(newMonth);
      }
      return currentDate;
    }
  },
  methods:{
    getUserLevelDes(){
      // 获取会员等级说明
      getUserLevelDes().then(res=>{
        if(res.code == 1){
          this.LevelS = []
          for(let i = 0;i < res.data.s.length;i++){
            let info = res.data.s[i];
            let item = {}
            item.id = info.id;
            item.image = BusinessUtils.getLevelIcon(info.id);
            item.direct_num = info.num
            item.money = formatNumberWithCommas(Number(info.team_money).toFixed(0));
            item.rate = Number(info.rate).toFixed(0);
            item.child_num = info.use_num;
            item.child_level = BusinessUtils.getLevelIcon(info.level_id);
            this.LevelS.push(item)
          }

          this.LevelT = []
          for(let i = 0;i < res.data.t.length;i++){
            let info = res.data.t[i];
            let item = {}
            item.id = info.id;
            item.image = BusinessUtils.getLevelIcon(info.id);
            item.direct_num = info.num
            if(Number(info.team_money) <= 0){
              item.money = '';
            }else{
              item.money = formatNumberWithCommas(Number(info.team_money).toFixed(0));
            }
            
            item.rate = Number(info.rate).toFixed(0);
            item.child_num = info.use_num;
            item.child_level = BusinessUtils.getLevelIcon(info.level_id);

            if(i < res.data.t.length - 1){
              item.stockRights = this.$t('10代以后的成员享受团队日收入的 {rate}%', { rate: info.team_income });
            }else{
              item.stockRights = this.$t('享受SpaceAI团队日收入的 {rate}%', { rate: info.team_income });
            }
            
            this.LevelT.push(item)
          }
        }
      })
    },

    // 全局支付弹窗
    async showConfirms() {
      const result = await confirmDialog({
        title: this.$t('请输入支付密码'),
        confirmText: this.$t('确认'),
        cancelText: this.$t('取消'),
      })
      
      if (result) {
        // 用户点击了确认
        console.log('执行删除操作')
      } else {
        // 用户点击了取消
        console.log('取消删除')
      }
    },
    formatDate(date) {
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const year = date.getFullYear();
      return `${month}/${day}/${year}`;
    },
    onConfirm(date) {
      this.datePopShow = false;
      // 调用 formatDate 方法格式化日期
      this.today = this.formatDate(date);
    },
    getUserInfo(){
      getUserInfo({}).then(res=>{
        if(res.code == 1){
          this.userInfo = {
            name: res.data.nickname,
            account: res.data.username,
            yield: Number(res.data.level.rate || 0).toFixed(1),
            image: res.data.avatar || require("@/image/personalCenter/head.png"),  // 暂时使用这个
            totalAssets: Number(res.data.total_cm || 0).toFixed(4),
            currency: res.data.country_code,
            todayProfit: Number(res.data.fincnce_cm || 0).toFixed(4),
            todayRate: Number(res.data.fincnce_rate || 0).toFixed(2),
            level: res.data.level,
            created_at: res.data.created_at || '',
          }

          this.isLevelOn = res.data.user_level_switch == 1; // 等级功能是否开启

          this.currencyList[0].balance = Number(res.data.usdt || 0).toFixed(4);
          this.currencyList[1].balance = Number(res.data.usdc || 0).toFixed(4);
          this.currencyList[2].balance = Number(res.data.susd || 0).toFixed(4);
          this.currencyList[3].balance = Number(res.data.sat || 0).toFixed(4);
          this.currencyList[0].price = Number(res.data.usdt_cm || 0).toFixed(4);
          this.currencyList[1].price = Number(res.data.usdc_cm || 0).toFixed(4);
          this.currencyList[2].price = Number(res.data.susd_cm || 0).toFixed(4);
          this.currencyList[3].price = Number(res.data.sat_cm || 0).toFixed(4);

          if(res.data.is_pay_password == 0){
            this.$toast.fail(this.$t('请设置支付密码'));
          }
        }else{
          this.$toast.fail(res.msg);
        }
      })
      this.getCouponList()
    },
    showLevelPop(){

    },
    getCouponList(){
      getInvestmentInfo().then(res=>{
        if(res.code == 1){
          this.couponList = res.data.coupon.map(item=>{
            return {
              id: item.id,
              price: Number(item.sub_money || 0).toFixed(2),
              currency: item.currency_name,
              meet: Number(item.use_money || 0).toFixed(2),
              name: item.name,
              startTime: item.start_time_day,
              endTime: item.end_time_day,
              status: Number(item.status)+1, // 1: 未使用 2: 已使用 3: 已过期
            }
          })
        }else{
          this.$toast.fail(res.msg);
        }
      })
    },
    handleImageError(event){
      event.target.src = this.defaultImage;
      event.target.onerror = null; // 防止备用图也出错时循环报错
    },
    goPersonalSetting(){
      // 前往设置
      if(this.$route.name != 'PersonalSetting'){
        this.$router.push({name: 'PersonalSetting'});
      }
    },
    goAiQuantization(id){
      // 前往ai量化
      if(id != 1) return 
      if(this.$route.name != 'AiQuantization'){
        this.$router.push({name: 'AiQuantization'});
      }
    },
    goPersonalHistory(){
      // 前往历史记录
      if(this.$route.name != 'PersonalCenterHistory'){
        this.$router.push({
          name: 'PersonalCenterHistory',
          params:{
            id:1
          }
        });
      }
    },
    goSystemSettings(){
      // 前往系统设置
      if(this.$route.name != 'SystemSettings'){
        this.$router.push({name: 'SystemSettings'});
      }
    },
    goGoupRoute(id){
      switch(id){
        case 1:
          // 前往充值
          if(this.$route.name != 'TopUp'){
            this.$router.push({name: 'TopUp'});
          }
          break;
        case 2:
          // 前往提现

          if(this.$store.state.userStore.canWithdraw){
            // 传递user的id，用于查询账户信息
            if(this.$route.name != 'WithdrawDeposit'){
            // 传递user的id，用于查询账户信息
            this.$router.push({
              name: 'WithdrawDeposit' , 
              params:{
                currency: 'USDT'
              }
            });
          }
          }else{
            this.$toast.fail(this.$t('需要持有一个正在运行中的有效订单'));
          }

          break;
        case 3:
          // 前往闪兑
          if(this.$route.name != 'FlashExchange'){
            // 传递user的id，用于查询账户信息
            this.$router.push(
              {
                name: 'FlashExchange',
                params: {
                  id:1
                }
              });
          }
          break;
        default:
          break;
      }
    },
    goCurrencyRoute(val){
      // 前往币种详情
      if(this.$route.name != 'CurrencyDetail'){
        sessionStorage.setItem('CurrencyDetail', JSON.stringify(val));
        this.$router.push({
          name: 'CurrencyDetail',
          params: { 
            value : val
          }
        })
      }
    },
    goInvite(){
      // 前往邀请
      if(this.$route.name != 'PersonalSettingLevel'){
        this.$router.push({
          name: 'PersonalSettingLevel',
        })
      }
    },

    getLevelIcon(levelId) {
      // 获取等级图标
      return BusinessUtils.getLevelIcon(levelId);
    },

    clickLevelIcon() {
      // 点击等级图标
      if (this.isLevelOn) {
        this.levelPopShow = true;
      }
    }
  }
};
</script>

<style lang="less">
@import "@/assets/styles/personalCenter/index.less";
</style>